import json
import re

from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from users.models import User


# Create your views here.
class UsernameCountView(View):
    def get(self, request, username):
        """
        判断用户名是否重复
        :param request:请求对象
        :param username:用户名
        :return:Json
        """
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        """
        判断手机号是否重复
        :param request:请求对象
        :param mobile: 手机号
        :return: Json
        """
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    def post(self, request):
        # 1.接收参数：请求体中的JSON数据request.body
        json_dict = json.loads(request.body.decode())

        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')

        if not all([username, password, password2, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数!'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式有误!'})
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '密码输入不一致!'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号码格式有误!'})

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败!'})

        # 实现状态保持
        login(request, user)

        return JsonResponse({'code': 0, 'errmsg': '注册成功!'})
